package com.ourhours.message.rpc.reference.huaxin;

import com.ourhours.message.rpc.reference.huaxin.dto.MessageDto;
import com.ourhours.message.utils.SSLClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public class HuaxinRpc {
    private static final Logger LOGGER = LoggerFactory.getLogger(HuaxinRpc.class);

    private static HttpClient httpclient;



    public MessageDto send(String url,String outerAppKey,String outerSecret,String phone,String content) throws Exception {
        try{
            Long start=System.currentTimeMillis();
            httpclient = new SSLClient();
            //获取短信账号信息，在上一步获取
            //组装Post数据
            HttpPost post = buildPost(url,outerAppKey,outerSecret,phone,content);
            Long startTime = System.currentTimeMillis();
            //发送https请求
            HttpResponse response = httpclient.execute(post);
            HttpEntity entity = response.getEntity();
            // 将字符转化为XML
            String returnString= EntityUtils.toString(entity, "UTF-8");
            Document doc = DocumentHelper.parseText(returnString);
            // 获取根节点
            Element rootElt = doc.getRootElement();
            // 获取根节点下的子节点的值
            String returnstatus = rootElt.elementText("returnstatus").trim();
            String message = rootElt.elementText("message").trim();
            String remainpoint = rootElt.elementText("remainpoint").trim();
            String taskID = rootElt.elementText("taskID").trim();
            String successCounts = rootElt.elementText("successCounts").trim();


            MessageDto messageDto = new MessageDto();
            messageDto.setReturnstatus(returnstatus);
            messageDto.setMessage(message);
            messageDto.setRemainpoint(remainpoint);
            messageDto.setTaskID(taskID);
            messageDto.setSuccessCounts(successCounts);
            Long end = System.currentTimeMillis();
            LOGGER.info("HuaxinRpc.send==>华信发送短信参数:{},{},{},{},{},结果:{},耗时:{}",url,outerAppKey,outerSecret,phone,content,returnstatus,end-start);
            return messageDto;
        }catch (Exception e){
            LOGGER.info("HuaxinRpc.send==>华信发送短信异常,参数:{},{},{},{},{},异常:{}",url,outerAppKey,outerSecret,phone,content,e);
            return null;
        }

    }

    public HttpPost buildPost(String url,String outerAppKey,String outerSecret,String phone,String content) throws UnsupportedEncodingException {
        HttpPost post = new HttpPost(url);
        post.setHeader("Content-type", "application/x-www-form-urlencoded;charset=utf-8");
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("action","send"));
        nvps.add(new BasicNameValuePair("userid", ""));
        nvps.add(new BasicNameValuePair("account", outerAppKey));
        nvps.add(new BasicNameValuePair("password", outerSecret));
        nvps.add(new BasicNameValuePair("mobile", phone));		//多个手机号用逗号分隔
        nvps.add(new BasicNameValuePair("content", "【全时】"+content));
        nvps.add(new BasicNameValuePair("sendTime", ""));
        nvps.add(new BasicNameValuePair("extno", ""));
        post.setEntity(new UrlEncodedFormEntity(nvps,HTTP.UTF_8));
        return post;
    }
}
